package com.threeti.mecool.web.controller;

import com.threeti.mecool.core.application.acl.EmployeeService;
import com.threeti.mecool.core.application.acl.UserService;
import com.threeti.mecool.core.domain.model.acl.User;
import com.threeti.mecool.core.domain.model.plan.pojo.Job;
import com.threeti.mecool.core.domain.model.plan.pojo.Plan;
import com.threeti.mecool.core.domain.model.plan.pojo.PlanJob;
import com.threeti.mecool.core.domain.model.plan.pojo.PlanProject;
import com.threeti.mecool.core.infrastructure.persistence.acl.UserRepository;
import com.threeti.mecool.web.util.WebResponse;
import org.apache.commons.lang.time.DateUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/subordinate")
public class SubordinatePlanController {

	public static final Logger logger = LoggerFactory.getLogger(SubordinatePlanController.class);

	@Autowired
	UserService userService;

	@Autowired
	UserRepository userRepository;

	@Autowired
	EmployeeService empService;

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/planAssignForm.html")
	public void planAssignForm(Map modelMap) {
		User user = userRepository.findByloginName(userService.getUserFromSession().getLoginName());

        List<String[]> list = empService.getProjectCodeLoginNameDisplayName_subOf(user.getEmployee().getEmpId().toString());
        Map<String, List<Map<String, String>>> employeeMap = new HashMap<String, List<Map<String, String>>>();
        for (String[] val : list) {
            String projectCode = val[0];
            String loginName = val[1];
            String displayName = val[2];
            List<Map<String, String>> userList = employeeMap.get(projectCode);
            if (userList == null) {
                userList = new LinkedList<Map<String, String>>();
                employeeMap.put(projectCode, userList);
            }
            Map<String, String> userMap = new HashMap<String, String>();
            userMap.put("loginName", loginName);
            userMap.put("displayName", displayName);
            userList.add(userMap);
        }

//		List<ProjectEmployee> emps = empService.findSubordinateEmployeesOfUser(user);
//		Map<String,List> employeeMap=new HashMap<String,List>();
//		for (ProjectEmployee projectEmployee : emps) {
//			Project project = projectEmployee.getProject();
//			String projectCode = project.getCode();
//			if(!employeeMap.containsKey(projectCode)){
//				employeeMap.put(projectCode,new ArrayList());
//			}
//
//			User employeeUser = userRepository.findByEmployeeEmpId(projectEmployee.getEmpId());
//			if(employeeUser==null){
//				continue;
//			}
//			Map userMap=new HashMap();
//			userMap.put("loginName", employeeUser.getLoginName());
//			userMap.put("displayName", employeeUser.getDisplayName());
//			employeeMap.get(projectCode).add(userMap);
//		}

		ObjectMapper mapper = new ObjectMapper();
		try {
			modelMap.put("employeeMap", mapper.writeValueAsString(employeeMap));
//			modelMap.put("users", userRepository.findAll());
		} catch (Exception e) {
			logger.error("", e);
		}
	}

    private static class _ProjectEmployee {
        String projectCode, loginName, displayName;

        _ProjectEmployee(String projectCode, String loginName, String displayName) {
            this.projectCode = projectCode;
            this.loginName = loginName;
            this.displayName = displayName;
        }
    }

	@SuppressWarnings({ "rawtypes" })
	@RequestMapping(value = "/planAssign.html")
	public String planAssign(Map modelMap,
						     String userLoginName,
						     String projectCode,
						     String storeCode,
						     Long jobId,
						     String planDate,
						     String startTime,
						     String endTime){

		try {
			Plan plan = Plan.optAssignedPlanBy(userLoginName, DateUtils.parseDate(planDate,new String[]{"yyyy-MM-dd"}));
            PlanProject planProject = plan.optPlanProjectByProjectCode(projectCode);
            //<editor-fold desc="create new planJob">
            PlanJob planJob = new PlanJob();
            Job job = Job.findById(jobId);
            planJob.setJob(job);
            planJob.setStoreCode(storeCode);
            planJob.setStartTime(DateUtils.parseDate(startTime,new String[]{"HH:mm:ss"}));
            planJob.setEndTime(DateUtils.parseDate(endTime,new String[]{"HH:mm:ss"}));
            planProject.addPlanJob(planJob);
            //</editor-fold>
			String logiName = userService.getUserFromSession().getLoginName();
			plan.setAssignedBy(logiName);
			plan.setConfirmedBy(logiName);
			plan.setStatus(Plan.STATUS_CONFIRM);
			plan.save();
            WebResponse.newInstance().buildModelMapData(modelMap);
        } catch (Exception e) {
			logger.error("",e);
            WebResponse.newInstance()
                    .setSuccess(false)
                    .setMsgBody(e.toString())
                    .buildModelMapData(modelMap);
		}
        return WebResponse.GLOBAL_SUBMIT_CALLBACK_PAGE;
	}


}
